package controller;

import model.DBUtil;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Locale;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String userName=req.getParameter("userName");
        String password=req.getParameter("password");
        String nickname=req.getParameter("nickname");
        String checkCode=req.getParameter("checkCode").toUpperCase();
        HttpSession session=req.getSession(false);
        if (session==null){
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write("{'msg':'session建立连接失败'}");
            return;
        }
        String inputCode= ((String) session.getAttribute("checkCode")).toUpperCase();
        if (!inputCode.equals(checkCode)){
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write("{'msg':'验证码输入错误'}");
            return;
        }
        if(userName==null||password==null||nickname==null||userName==""||password==""||nickname==""){
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write("{'msg':'必填项为空'}");
            return;
        }
        UserDao userDao=new UserDao();
        //判断userName是否已经存在
        User exist=userDao.queryInfoByUserName(userName);
        if (!(exist==null)){
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write("{'msg':'用户名已经存在'}");
            return;
        }
        User user=new User();
        user.setPassword(password);
        user.setNickName(nickname);
        user.setUserName(userName);
        userDao.addUser(user);
        session.setAttribute("user",user);
        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write("注册成功，正在跳转页面");
        resp.sendRedirect("login.html");
    }
}
